const path = require('path');
const fs = require('fs');

const {PORT} = require('./config');
const {IPv4Address} = require('../util/ip4address');

const uploadimg = async (ctx) => {
    return new Promise((resolve, reject) => {
        let remotefilePath = null;
        let filePath = '';
        if (ctx.request.files['file']) {
            // 创建可读流
            console.log(89, ctx.request.files['file']['path']);
            const reader = fs.createReadStream(ctx.request.files['file']['path']);
            filePath = `${path.resolve(__dirname, './public/upload/')}/${ctx.request.files['file']['name']}`;
            remotefilePath = `http://${IPv4Address}:${PORT}/upload/${ctx.request.files['file']['name']}`;
            // 创建可写流
            const upStream = fs.createWriteStream(filePath);
            // 可读流通过管道写入可写流
            reader.pipe(upStream);
        }
        resolve(remotefilePath)
    })
};

module.exports = uploadimg;
